package com.kaily.timemanager.data;


import android.content.Context;

import com.app.common.util.Logger;
import com.kaily.timemanager.view.ProgressCancelListener;
import com.kaily.timemanager.view.ProgressDialogHandler;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * 数据回调，此回调需要在UI线程运行
 *
 * @param <M>
 */
public class DataCallback<M> extends Subscriber<M> implements ProgressCancelListener {

    private static final String TAG = "DataCallback";

    private Context context;
    private ProgressDialogHandler mProgressDialogHandler;
    private DataListener dataListener;

    public DataCallback(Context context, DataListener dataListener, boolean isShowDialog) {
        this.context = context;
        this.dataListener = dataListener;
        if (isShowDialog) {
            mProgressDialogHandler = new ProgressDialogHandler(context, this, false);
        }

    }

    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            //httpException.response().errorBody().string()
            int code = httpException.code();
            String msg = httpException.getMessage();
            Logger.d(TAG, "code=" + code);
            if (code == 504) {
                msg = "网络不给力";
            }
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试";
            }
            if (this.dataListener != null) {
                this.dataListener.onFailure(msg);
            }

        } else {
            if (this.dataListener != null) {
                this.dataListener.onFailure(e.getMessage());
            }

        }
        if (this.dataListener != null) {
            this.dataListener.onFinish();
        }

    }

    @Override
    public void onNext(M model) {
        if (this.dataListener != null) {
            this.dataListener.onSuccess(model);
        }


    }

    @Override
    public void onCompleted() {
        dismissProgressDialog();
        if (this.dataListener != null) {
            this.dataListener.onFinish();
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        showProgressDialog();
    }

    private void showProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mProgressDialogHandler = null;
        }
    }

    @Override
    public void onCancelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }
}
